package com.rgs.ssm.dao;

import com.rgs.ssm.domain.Permission;
import com.rgs.ssm.domain.Role;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @author Ren Gaoshuai
 * @create 2021-05-29 9:16
 *
 * 角色的持久层接口
 **/
public interface IRoleDao {

    /**
     * 根据传过来的userId 回去到用户对应所有角色
     * @param userId
     * @return
     */
    @Select("select * from role where id in (select roleId from users_role where userId=#{userId} )")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions",column = "id",javaType = java.util.List.class,many = @Many(select = "com.rgs.ssm.dao.IPermissionDao.findPermissionByRoleId"))
    })
    List<Role> findRoleByUserId(Integer userId);

    /**
     * 查询所有的角色信息
     * @return
     */
    @Select("select * from role")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions",column = "id",javaType = java.util.List.class,many = @Many(select = "com.rgs.ssm.dao.IPermissionDao.findPermissionByRoleId"))
    })
    List<Role> findAll();


    /**
     * 根据角色id查询对应的角色信息
     * @param roleId
     * @return
     */
    @Select("select * from role where id = #{roleId}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions",column = "id",javaType = java.util.List.class,many = @Many(select = "com.rgs.ssm.dao.IPermissionDao.findPermissionByRoleId"))
    })
    Role findById(Integer roleId);

    /**
     * 根据角色id,返回该角色未有的权限信息（供添加权限使用）
     * @param roleId
     * @return
     */
    @Select("select * from permission where id not in ( select permissionId from role_permission where roleId = #{roleId})")
    List<Permission> findOtherPermission(Integer roleId);

    /**
     * 保存角色信息
     * @param role
     */
    @Insert("insert into role(roleName,roleDesc) values (#{roleName},#{roleDesc})")
    void saveRole(Role role);

    @Delete("delete from role where id = #{id}")
    void delete(Integer id);

    @Update("update role set roleName=#{roleName},roleDesc=#{roleDesc} where id = #{id}")
    void update(Role role);

    @Insert("insert into role_permission (roleId,permissionId) values (#{roleID},#{permissionId})")
    void addPermissionToRole(@Param("roleId") Integer roleId,@Param("permissionId") Integer permissionId);


}
